<!--
 * @Descripttion: your project
 * @version: 1.0
 * @Author: hongweixun
 * @Date: 2023-05-17 16:06:06
 * @LastEditors: liyin 2179253556@qq.com
 * @LastEditTime: 2025-08-29 17:19:44
-->
<template>
  <div class="card-handle-box">
    <Title :isbig="true">
      <template #title>
        套餐办理高峰期统计
      </template>
    </Title>
    <el-row type="flex" justify="end">
      <el-row class="btn-right-top-box">
        <el-col @click="choice(1)" :span="12" class="common-box-col" :class="choiceIndex == 1 ? 'is-active-box' : ''"
          style="border-radius: 2px 0 0 2px;">散点图</el-col>
        <el-col @click="choice(2)" :span="12" class="common-box-col" :class="choiceIndex == 2 ? 'is-active-box' : ''"
          style="border-radius: 0px 2px 2px 0px;">折线图</el-col>
      </el-row>
    </el-row>
    <el-row class="area-box" :style="{ height: props.screenCenterTwoHeight + 'px' }">
      <!-- 散点图 -->
      <div id="container1" ref="chartOneRef" v-show="choiceIndex == 1"></div>
      <!-- 折线图 -->
      <div id="container2" ref="chartTwoRef" v-show="choiceIndex == 2"></div>
    </el-row>
  </div>
</template>
<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import { PiniaStore } from '../store/index'
import * as echarts from 'echarts'
import $util from "../util/util"
import { todayPayTimeScatterPlot,todayPayTimeLineChart } from './Options/Api'
interface PropsType {
  //   是否需要更多按钮
  screenCenterTwoHeight?: any
  verify_code: string
}
const props = withDefaults(defineProps<PropsType>(), {
  screenCenterTwoHeight: 364,
  verify_code: ''
})
interface EmitType {
  (e: 'getZhexian'): void
  (e: 'getSandian'): void
}
const emit = defineEmits<EmitType>()
const store = PiniaStore()
const choiceIndex = ref(1)
// 切换图表
const choice = async(num: any) => {
  choiceIndex.value = num
  store.setChoiceIndex(num)
  if (num === 2) {
    await getTransactTimeZheXian()
  } else {
    await getTransactTime()
  }
  // await reloadChart()
}
// 获取时间散点图
const sandianList = ref<any>([])
const scatterData = ref<any>([])
const getTransactTime = async () => {
  const res: any = await todayPayTimeScatterPlot({
    verify_code:props.verify_code
  })
  if (res.code !== 1)  return false
  return new Promise(async (resolve) => {
    sandianList.value = res.data.list
    await getCharts()
    store.setLoddingStatus()
    resolve(undefined) // 所有操作完成后resolve
  })
}
const chartOneRef = ref<any>(null)
const chartTwoRef = ref<any>(null)
let myChart: any = null
let myChart2: any = null
const getCharts = async () => {
  let arr: any = []
  // 创建school_name到颜色的映射
  const schoolColorMap = new Map<string, string>()
  // 生成浅色系颜色的辅助函数
  const generateColor = (index: number) => {
    // 使用HSV色彩空间，通过改变色相值生成不同颜色
    const hue = (index * 60) % 360; // 每隔60度取一个色相
    const saturation = 0.3 + Math.random() * 0.3; // 降低饱和度：40%-70%，生成更浅的颜色
    const value = 0.9 + Math.random() * 0.15; // 提高亮度：85%-100%，确保颜色更浅
    // 转换HSV到RGB
    const hsvToRgb = (h: number, s: number, v: number) => {
      h = h / 360;
      let r:any, g:any, b:any;
      const i = Math.floor(h * 6);
      const f = h * 6 - i;
      const p = v * (1 - s);
      const q = v * (1 - f * s);
      const t = v * (1 - (1 - f) * s);
      switch (i % 6) {
        case 0: { r = v; g = t; b = p; break; }
        case 1: { r = q; g = v; b = p; break; }
        case 2: { r = p; g = v; b = t; break; }
        case 3: { r = p; g = q; b = v; break; }
        case 4: { r = t; g = p; b = v; break; }
        case 5: { r = v; g = p; b = q; break; }
      }
      return `rgb(${Math.round(r * 255)}, ${Math.round(g * 255)}, ${Math.round(b * 255)})`;
    };
    return hsvToRgb(hue, saturation, value);
  };
  
  // 处理数据并为每个school_name分配颜色
  let colorIndex = 0;
  sandianList.value.forEach((item: any) => {
    if (!schoolColorMap.has(item.school_name)) {
      schoolColorMap.set(item.school_name, generateColor(colorIndex++));
    }
    arr.push({
      value: [item.xval, item.yval],
      itemStyle: {
        color: schoolColorMap.get(item.school_name)
      },
      name: item.school_name
    });
  });
  
  scatterData.value = arr;
  myChart = echarts.init(chartOneRef.value)
  const option = {
    xAxis: {
      type: "category",
      data: scatterData.value.map((item: any) => item.value[0]), // 绑定x类
      splitArea: { show: false }, //去除网格区域，否则会有一片区域
      axisLabel: {
        // 设置x轴的文字的样式
        textStyle: {
          show: true,
          color: "#ffffff",
          fontSize: $util.fontSize(15),
        },
        margin: $util.fontSize(18),
      },
      axisLine: {
        show: true, // 把x轴从实线变成虚线
        lineStyle: {
          // 设置x轴线条样式的颜色
          color: "#2F5A8D",
          width: 1,
          type: "solid",
        },
      },
      splitLine: {
        //去除网格线
        show: false,
        lineStyle: {
          color: "rgba(255,255,255,0.15)",
          type: "dashed", //设置网格线类型 dotted：虚线   solid:实线
        },
      },
      axisTick: {
        show: false, // 新增：隐藏x轴刻度线
      },
      scale: true, // 设置数据自动缩放，要不然数据多的话就堆一块了
    },
    yAxis: {
      type: "value",
      nameTextStyle: {
        color: "#ffffff",
        nameLocation: "end",
      },
      axisTick: {
        show: false, // 去掉y轴的凸出刻度
      },
      axisLine: {
        show: false, // 把y轴从实线变成虚线
      },
      splitLine: {
        //去除网格线
        show: true,
        lineStyle: {
          color: "rgba(255,255,255,0.15)",
          type: "dashed", //设置网格线类型 dotted：虚线   solid:实线
        },
      },
      splitArea: { show: false }, //去除网格区域
      axisLabel: {
        // 设置y轴的文字的样式
        textStyle: {
          show: true,
          color: "#ffffff",
          fontSize: $util.fontSize(15),
        },
      },
      scale: true, // 设置数据自动缩放，要不然数据就堆一块了
      // show: false,
    },
    grid: {
      // 位置
      show: true,
      x: 36,
      y: 30,
      x2: 10,
      y2: 36,
      borderWidth: 0, // 去除图表的边框
    },
    tooltip: {
      trigger: 'axis',
      showContent: true, // 是否显示提示框浮层
      backgroundColor: "#fff",
      extraCssText: "box-shadow: 0px 9px 28px 1px rgba(0,0,0,0.05);",
      formatter: function (obj: any) {
        console.log(obj, 'obj')
        return (
          `<span style='font-size: 12px;
                        font-family: Source Han Sans CN, Source Han Sans CN;
                        font-weight: bold;
                        color:#000000;width:100%;text-align: center;margin-bottom:4px;display:inline-block;text-align: left;'>${sandianList.value[obj[0].dataIndex].school_name}</span>` +
          `<br>` + `<span style="display:flex; justify-content:space-between; margin-bottom: 2px">
                      <span><span style="display:inline-block;font-size:12px;vertical-align: middle;color:#000000;">时分</span></span>
                      <span style="display:inline-block;margin-left:20px;font-size:12px;vertical-align: middle;color:#333333;">${sandianList.value[obj[0].dataIndex].xval}</span>
                    </span>` + `<span style="display:flex; justify-content:space-between; margin-bottom: 2px">
                      <span><span style="display:inline-block;font-size:12px;vertical-align: middle;color:#000000;">秒：</span></span>
                      <span style="display:inline-block;margin-left:20px;font-size:12px;vertical-align: middle;color:#333333;">${sandianList.value[obj[0].dataIndex].yval}</span>
                    </span>`+ `<span style="display:flex; justify-content:space-between; margin-bottom: 2px">
                     <span><span style="display:inline-block;font-size:12px;vertical-align: middle;color:#000000;">缴费金额：</span></span>
                      <span style="display:inline-block;margin-left:20px;font-size:12px;vertical-align: middle;color:#333333;">${sandianList.value[obj[0].dataIndex].amount}元</span>
                    </span>`
        )
      },
      axisPointer: {
        show: true,
        type: 'cross',
        lineStyle: {
          type: 'dashed',
          width: 1
        }
      }
    },
    series: [
      {
        name: "",
        symbolSize: 10, // 散点图的大小
        data: scatterData.value,
        type: "scatter", // 类型为散点图
        itemStyle: {
          // 设置散点图的透明度
          //   opacity: 0.85,
        },
      }
    ],
    // color: ["#007FFF"], // 控制圆环图的颜色
    legend: {
      right: 10,
      itemGap: 20,
      itemWidth: 8,
      itemHeight: 8,
      data: ["初中部"],
      textStyle: {
        fontSize: 12,
        color: "#ffffff",
      },
    },
  }
  myChart.setOption(option)
}
// 折线图
// 获取折线图的数据
const zhexianList = ref<any>([])
const getTransactTimeZheXian = async () => {
  const res: any = await todayPayTimeLineChart({
    verify_code:props.verify_code
  })
  if (res.code !== 1) {
    return false
  }
  return new Promise(async (resolve) => {
    let arr: any = []
    if(res.data&&res.data.list) {
      Object.keys(res.data.list).forEach((key: any) => {
        arr.push({
          pay_time: key,
          pay_amount: res.data.list[key].pay_amount,
          pay_number: res.data.list[key].pay_number
        })
      })
    }
    zhexianList.value = arr
    await getCharts2()
    resolve(undefined) // 所有操作完成后resolve
})
}
const getCharts2 = async () => {
  myChart2 = echarts.init(chartTwoRef.value)
  let ListTwo: any = []
  let ListIndex: any = []
  zhexianList.value.map((item: any) => {
    ListTwo.push(item.pay_amount) // 通话时长 min/分钟
    ListIndex.push(item.pay_time) // 排序
  })
  let color = ['#61D7A7']
  let option = {
    color: color,
    title: {
      left: 'left',
      text: '概率',
      show: false
    },
    tooltip: {
      trigger: 'axis',
      showContent: true, // 是否显示提示框浮层
      backgroundColor: "#fff",
      extraCssText: "box-shadow: 0px 9px 28px 1px rgba(0,0,0,0.05);",
      formatter: function (obj: any) {
        console.log(obj, 'obj')
        return (
          `<span style='font-size: 12px;
                        font-family: Source Han Sans CN, Source Han Sans CN;
                        font-weight: bold;
                        color:#000000;width:100%;text-align: center;margin-bottom:4px;display:inline-block;text-align: left;'>${zhexianList.value[obj[0].dataIndex].pay_time}</span>` +
          `<br>` + `<span style="display:flex; justify-content:space-between; margin-bottom: 2px">
                      <span><span style="display:inline-block;font-size:12px;vertical-align: middle;color:#000000;">总金额</span></span>
                      <span style="display:inline-block;margin-left:20px;font-size:12px;vertical-align: middle;color:#333333;">${zhexianList.value[obj[0].dataIndex].pay_amount}</span>
                    </span>` + `<span style="display:flex; justify-content:space-between; margin-bottom: 2px">
                      <span><span style="display:inline-block;font-size:12px;vertical-align: middle;color:#000000;">支付人数：</span></span>
                      <span style="display:inline-block;margin-left:20px;font-size:12px;vertical-align: middle;color:#333333;">${zhexianList.value[obj[0].dataIndex].pay_number}</span>
                    </span>`
        )
      },
      axisPointer: {
        show: true,
        type: 'cross',
        lineStyle: {
          type: 'dashed',
          width: 1
        }
      }
    },
    grid: {
      show: false,
      top: '30',
      bottom: '45',
      right: $util.fontSize(20),
      left: $util.fontSize(20)
    },
    xAxis: {
      type: 'category',
      data: ListIndex,
      splitArea: { show: false }, //去除网格区域，否则会有一片区域
      axisLabel: {
        // 设置x轴的文字的样式
        textStyle: {
          show: true,
          color: "#ffffff",
          fontSize: $util.fontSize(15),
        },
        margin: $util.fontSize(18),
      },
      axisLine: {
        show: true, // 把x轴从实线变成虚线
        lineStyle: {
          // 设置x轴线条样式的颜色
          color: "#2F5A8D",
          width: 1,
          type: "solid",
        },
      },
      splitLine: {
        //去除网格线
        show: false,
        lineStyle: {
          color: "rgba(255,255,255,0.15)",
          type: "dashed", //设置网格线类型 dotted：虚线   solid:实线
        },
      },
      axisTick: {
        show: false, // 新增：隐藏x轴刻度线
      },
      scale: true, // 设置数据自动缩放，要不然数据多的话就堆一块了
    },
    yAxis: {
      type: 'value',
      nameTextStyle: {
        color: "#ffffff",
        nameLocation: "end",
      },
      axisTick: {
        show: false, // 去掉y轴的凸出刻度
      },
      axisLine: {
        show: false, // 把y轴从实线变成虚线
      },
      splitLine: {
        //去除网格线
        show: true,
        lineStyle: {
          color: "rgba(255,255,255,0.15)",
          type: "dashed", //设置网格线类型 dotted：虚线   solid:实线
        },
      },
      splitArea: { show: false }, //去除网格区域
      axisLabel: {
        // 设置y轴的文字的样式
        textStyle: {
          show: true,
          color: "#ffffff",
          fontSize: $util.fontSize(15),
        },
      },
      scale: true, // 设置数据自动缩放，要不然数据就堆一块了
      // show: false,
    },
    series: [
      {
        data: ListTwo,
        type: 'line',
        smooth: true,
        lineStyle: {
          width: 0
        },
        showSymbol: false,
        areaStyle: {
          opacity: 0.7,
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: 'rgba(54,235,201,0.68)'
            },
            {
              offset: 1,
              color: 'rgba(24,130,255,0.68)'
            }
          ])
        },
      }
    ]
  }
  myChart2.setOption(option)
}
//重新加载图表
const reloadChart = async () => {
  disposeChart()
  if (choiceIndex.value == 1) {
    await getCharts()
  } else {
    await getCharts2()
  }
}
const disposeChart = () => {
  if (myChart) {
    myChart.dispose()
  }
  if (myChart2) {
    myChart2.dispose()
  }
}
onMounted(async () => {
  window.addEventListener('resize', () => {
    // 计算高度
    setTimeout(async () => {
      await reloadChart()
    }, 500);
  })
})
defineExpose({ getTransactTime,getTransactTimeZheXian })
</script>
<style lang="scss" scoped>
.area-box {
  width: 100%;
  position: relative;

  #container1 {
    width: 100%;
    height: 100%;
  }

  #container2 {
    width: 100%;
    height: 100%;
  }
}

.btn-right-top-box {
  color: var(--el-color-white);
  border-radius: 2px;
  width: 150px;
  margin-top: 24px;

  .common-box-col {
    border: 1px solid #3b94fe;
    padding: 5px 10px;
    height: 32px;
    font-size: 14px;
    text-align: center;
    cursor: pointer;
    color: #3B94FE;
  }

  .common-box-col.is-active-box {
    padding: 5px 10px;
    background-color: #3b94fe;
    color: #ffffff;
  }
}
</style>
